package titt.io.reader.util;

import java.io.InputStream;
import java.nio.ByteBuffer;

public class LineReader {

	private final ByteBuffer bb = ByteBuffer.allocate(2048); //512 should be enough but you never know
	private InputStream in;
	private byte[] newline;
	
	public LineReader(InputStream in, byte[] newline) {
		this.in = in;
		this.newline = newline;
	}
	
	private boolean bytesIsNewline() {
		for(int i = 0; i < newline.length; i++)
			if(bb.get(bb.position()-newline.length+i) != newline[i]) return false;
		return true;
	}
	
	public byte[] readLine() throws Exception {
		bb.clear();

		int cur;
		while((cur = in.read()) != -1) {
			bb.put((byte)cur);
			if(bb.position() > 1 && bytesIsNewline()) {
				bb.position(bb.position()-2);
				return getBytes();
			}
		}
		
		if(bb.position() == 0)
			return null;

		return getBytes();
	}
	
	private byte[] getBytes() {
		byte[] res = new byte[bb.position()];
		bb.flip();
		bb.get(res, 0, res.length);
		return res;
	}
}
